package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
//搜索相关产品
public class SearchProductServlet extends HttpServlet {
    private static final String SEARCH_PRODUCT = "/WEB-INF/jsp/catalog/SearchProducts.jsp";
    private String keyword;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取搜索框中的关键词
        keyword = request.getParameter("keyword");
        CatalogService service = new CatalogService();

        //获得搜索的产品列表
        List<Product> productList = service.searchProductList(keyword);
        HttpSession session = request.getSession();
        session.setAttribute("productList",productList);

        Account account = (Account) session.getAttribute("account");

        if(account!= null){
            //时间
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = tempDate.format(new java.util.Date());
            //信息
            String info = "用户"+account.getUsername()+"查找关键词" + keyword;
            Log log = new Log(account.getUsername(),datetime,info);
            //添加log
            new AccountService().addLog(log);

        }

        request.getRequestDispatcher(SEARCH_PRODUCT).forward(request,response);
    }
}